package main

import (
	"fmt"
	"net"
	"net/http"
	"net/http/httputil"
	"os/signal"
	"runtime"
	"runtime/debug"
	"time"

	"go.uber.org/zap"

	//gin web服务框架
	"strings"

	"os"

	"github.com/gin-gonic/gin"

	"github.com/tus/tusd/pkg/filestore"
	tusd "github.com/tus/tusd/pkg/handler"
)

type (
	//反馈信息封装
	ResponseResult struct {
		Code int  `json:"code,int"` //0成功 不是0失败或警告
		Data interface{} `json:"data"` //返回数据
		Msg  string `json:"msg"`//失败信息
		RowCount int `json:"row_count,int"`//返回行数
	}
)

var logger *zap.Logger

func InitLogger() {
	logger, _ = zap.NewProduction()
}

// GinLogger 接收gin框架默认的日志
func GinLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		logger.Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}

// GinRecovery recover掉项目可能出现的panic
func GinRecovery(logger *zap.Logger, stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// Check for a broken connection, as it is not really a
				// condition that warrants a panic stack trace.
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					logger.Error(c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					// If the connection is dead, we can't write a status to it.
					c.Error(err.(error)) // nolint: errcheck
					c.Abort()
					return
				}

				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}
				c.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		c.Next()
	}
}
func main() {
	var cstZone = time.FixedZone("CST", 8*3600) // 东八
	time.Local = cstZone

	InitLogger()
	//多核
	runtime.GOMAXPROCS(runtime.NumCPU())

	router := gin.Default()

	gin.SetMode(gin.ReleaseMode) // 线上模式，控制台不会打印信息

	// 注册zap相关中间件
	router.Use(GinLogger(logger), GinRecovery(logger, true))


	 //健康检查
	 router.GET("/health",func(context *gin.Context){
		context.JSON(http.StatusOK, ResponseResult{Code: 0, Data: "", Msg: "ok"})
	})
	//图标
	router.StaticFile("/favicon.ico", "./static/favicon.ico")
	//静态文件
	router.Static("/static", "./static")

	router.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusPermanentRedirect,"/static/index.html")
	})

    os.MkdirAll("./uploads", os.ModePerm)
	tus_store := filestore.FileStore{
		Path: "./uploads",
	}
	tus_composer := tusd.NewStoreComposer()
	tus_store.UseIn(tus_composer)

	tus_handler, err := tusd.NewHandler(tusd.Config{
		BasePath:              "/files/",
		StoreComposer:         tus_composer,
		NotifyCompleteUploads: true,
	})
	if err != nil {
		logger.Panic(fmt.Sprintf("Unable to create handler: %s", err.Error()))
	}

	go func() {
		for {
			event := <-tus_handler.CompleteUploads
			
			fmt.Printf("Upload %s finished\n", event.Upload.ID)
		}
	}()
	
    router.Any("/files/",func(c *gin.Context) {
		h := http.StripPrefix("/files/", tus_handler)
		h.ServeHTTP(c.Writer, c.Request)
	})
	router.Any("/files/:id",func(c *gin.Context) {
		h := http.StripPrefix("/files/", tus_handler)
		h.ServeHTTP(c.Writer, c.Request)
	})
	//

	
	

	//外部访问 http
	go func() {
		_ = router.Run("0.0.0.0:17878")
	}()

	//Crtl +c停止
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
}
